import jsonResult from './json-result'

export const get = (key) => {
    if (!key || typeof key !== 'string') {
        return null
    }

    return localStorage.getItem(key)
}

export const getData = (key) => {
    let data

    const result = jsonResult(() => {
        data = JSON.parse(get(key))
    })

    return result.success ? data : null
}

export const set = (key, data) => {
    var result = jsonResult(() => {
        if (!key || typeof key !== 'string') {
            throw '键值有误'
        }

        if (!data) {
            throw '存值有误'
        }

        const isObject = typeof data === 'object'

        if (isObject) {
            localStorage.setItem(key, JSON.stringify(data))
            return
        }

        localStorage.setItem(key, data)
    })

    return result
}

export const clear = (key) => {
    const result = jsonResult(() => {
        localStorage.removeItem(key)
    })

    return result
}

export const clearAll = () => {
    const result = jsonResult(() => {
        localStorage.clear()
    })

    return result
}


export default {
    get,
    getData,
    set,
    clear,
    clearAll
}